package com.remoter.monitor.internal;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.remoter.api.consumer.IConsumerService;
import com.remoter.api.context.IContextService;
import com.remoter.api.context.support.Exporter;
import com.remoter.api.extension.annotation.ExtensionName;
import com.remoter.api.monitor.IMonitorService;
import com.remoter.api.provider.IProviderService;

@ExtensionName("internal")
public class InternalMonitorService implements IMonitorService{

	private IContextService contextService;
	private IProviderService providerService;
	private IConsumerService consumerService;
	
	@Override
	public void start(IContextService contextService,IProviderService providerService,IConsumerService consumerService){
		this.contextService = contextService;
		this.providerService = providerService;
		this.consumerService = consumerService;
	}

	@Override
	public void close(){
		if(null != this.contextService){
			this.contextService = null;
		}
		if(null != this.providerService){
			this.providerService = null;
		}
		if(null != this.consumerService){
			this.consumerService = null;
		}
	}
	
	@Override
	public InetSocketAddress getBind(){
		return this.providerService.getBindSocketAddress();
	}
	
	@Override
	public List<String> getAllExporters() {
		List<String> result = new ArrayList<String>();
		Map<String,Exporter> exporters = this.contextService.getExporters();
		for(Entry<String,Exporter> entry : exporters.entrySet()){
			Exporter exporter = entry.getValue();
			String path = String.format("%s(%s)",exporter.getType(),exporter.getBean());
			if(!result.contains(path)){
				result.add(path);
			}
		}
		return result;
	}

}